#pragma once
#include <vector>
#include <Worker.h>
#include "Service.h"
#include "SocketWorker.h"
#include <unordered_map>
#include "Conn.h"

class Worker;

class Sunnet {
    public:
        static Sunnet* inst;
        unordered_map<uint32_t, shared_ptr<Service>> services;
        uint32_t maxId = 0;
        pthread_rwlock_t servicesLock;

    public:
        Sunnet();
        void Start();
        //等待运行
        void Wait();
        uint32_t NewService(shared_ptr<string> type);
        void KillService(uint32_t id);
        void Send(uint32_t toId, shared_ptr<BaseMsg> msg);
        shared_ptr<Service> PopGlobalQueue();
        void PushGlobalQueue(shared_ptr<Service> srv);
        shared_ptr<BaseMsg> MakeMsg(uint32_t source, char* buff, int len);
        void CheckAndWeakUp();
        void WorkerWait();

        //增删查Conn
        int AddConn(int fd, uint32_t id, Conn::TYPE type);
        shared_ptr<Conn> GetConn(int fd);
        bool RemoveConn(int fd);

        int Listen(uint32_t port, uint32_t serviceId);
        void CloseConn(uint32_t fd);

    private:
        //工作线程
        int WORKER_NUM = 3;
        vector<Worker*> workers;
        vector<thread*> workerThreads;
        queue<shared_ptr<Service>> globalQueue;
        int globallen = 0;
        pthread_spinlock_t globalLock;
        pthread_mutex_t sleepMtx;
        pthread_cond_t sleepCond;
        int sleepCount = 0;

        //Socket线程
        SocketWorker* socketWorker;
        thread* socketThread;

        //Conn列表
        unordered_map<uint32_t, shared_ptr<Conn>> conns;
        pthread_rwlock_t connsLock; //读写锁

    private:
        //开启工作线程
        void StartWorker();
        //开启Socket线程
        void StartSocket();
        //获取服务
        shared_ptr<Service> GetService(uint32_t id);
};